package com.myapp.web.action.product;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.SessionAware;

import com.myapp.model.entity.product.Product;
import com.myapp.service.product.ProductBo;
import com.myapp.util.Constants;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class ProductAction extends ActionSupport implements ModelDriven<ProductForm> ,ServletRequestAware,SessionAware
{
	private static final long serialVersionUID = -1361465162506350513L;	

	private ProductForm product = new ProductForm();
	
	private Map<String,Object> sessionMap;
	
	HttpServletRequest request;
	
	private ProductBo prodBo;
	
	@Override
	public ProductForm getModel(){
		return product;
	}
	
	public void setProdBo(ProductBo prodBo){
		this.prodBo = prodBo;
	}

	public String addProd() throws Exception{
		Product prod = product.getProduct();
		Integer prodId = getProdId();
		if(prodId != null){
			prod.setId(prodId);
		}
		prodBo.addProduct(product.getProduct());
		return SUCCESS;
	}
	
	private Integer getProdId(){
		System.out.println("Product *****" + request.getSession().getId());
		Object val = ActionContext.getContext().getSession().get(Constants.PROD_ID_SESSION_KEY);
		return (Integer)sessionMap.get(Constants.PROD_ID_SESSION_KEY);
		
	}
	
	public String index() throws Exception{
		return SUCCESS;
	}
	
	public String execute() throws Exception {
		Product prod = product.getProduct();
		Integer prodId = getProdId();
		if(prodId != null){
			prod.setId(prodId);
		}
		prodBo.addProduct(product.getProduct());
        return SUCCESS;
    }
	
	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;		
	}

	@Override
	public void setSession(Map<String, Object> session) {
		sessionMap = session;
		if(!session.isEmpty()){
			Set<Entry<String,Object>> set = session.entrySet();
			Iterator<Entry<String,Object>> it = set.iterator();
			while(it.hasNext()){
				Entry<String,Object> e = it.next();
				System.out.println("key: " + e.getKey() + "value : " + e.getValue().toString());
			}
		}
	}
}
